package net.asfun.jvalog.service;

import java.util.ArrayList;
import java.util.List;

import net.asfun.jvalog.common.JdoerFactory;
import net.asfun.jvalog.entity.Sort;
import net.asfun.jvalog.resource.SortDao;
import net.asfun.jvalog.util.Bridge;
import net.asfun.jvalog.util.Unifier;
import net.asfun.jvalog.util.UpdateManager;
import net.asfun.jvalog.vo.Category;
import net.asfun.jvalog.vo.Pager;
import net.asfun.jvalog.vo.Post;


import com.google.appengine.api.datastore.Key;

public class CategoryService {

	
	public static List<Category> listAll() {
		List<Category> categories = new ArrayList<Category>();
		for(Sort sort : SortDao.listAll()) {
			categories.add(new Category(sort));
		}
		return categories;
	}

	public static Category getBySlogan(String slogan) {
		return new Category(SortDao.getBySlogan(slogan));
	}

	public static List<Post> listPublished(Category category, Pager pager) {
		return category.listPublishedPosts(pager);
	}

	public static Object listAll(Pager pager) {
		List<Category> categories = new ArrayList<Category>();
		for(Sort sort : SortDao.listAll(pager)) {
			categories.add(new Category(sort));
		}
		return categories;
	}

	public static void delete(Long id) {
		Sort sort = JdoerFactory.jdoSort.load(id);
		if ( sort != null ) {
			Unifier.unsetUnique(sort.getKey(), "slogan");
			JdoerFactory.jdoRelation.delete(Bridge.getRelationsByRight(sort.getKey(), Bridge.POST_CATEGORY));
			JdoerFactory.jdoSort.delete(sort);
			UpdateManager.enableCacheTask();
		}
	}

	public static void addCategory(Sort sort) {
		sort.setSlogan(uniqueURI(sort.getSlogan()));
		JdoerFactory.jdoSort.save(sort);
		Unifier.setUnique(sort.getKey(), "slogan", sort.getSlogan());
		UpdateManager.enableCacheTask();
	}
	
	private static String uniqueURI(String slogan) {
		if ( ! Unifier.isUnique("Sort", "slogan", slogan)) {
			slogan += "~1";
			return slogan = uniqueURI(slogan);
		}
		return slogan;	
	}
	
	private static String uniqueURI(String slogan, Key key) {
		if ( ! Unifier.isUnique(key, "slogan", slogan)) {
			slogan += "~1";
			return slogan = uniqueURI(slogan, key);
		}
		return slogan;	
	}

	public static void update(Sort sort) {
		sort.setSlogan(uniqueURI(sort.getSlogan(), sort.getKey()));
		JdoerFactory.jdoSort.save(sort);
		Unifier.setUnique(sort.getKey(), "slogan", sort.getSlogan());
		UpdateManager.enableCacheTask();
	}

	public static Category getById(Long id) {
		return new Category(JdoerFactory.jdoSort.load(id));
	}

}
